//
//  CajoleryViewController.m
//  OurJourney
//
//  Created by 李沛池 on 2017/4/1.
//  Copyright © 2017年 Godlike. All rights reserved.
//

#import "CajoleryViewController.h"
#import "LPCDefine.h"
#import <MBProgressHUD+JDragon.h>
#import "LPCSettingManager.h"
#import "LPCInfoManager.h"

@interface CajoleryViewController ()<
UITextViewDelegate>

@end

@implementation CajoleryViewController
{
    BOOL _isAddRow; //是不是添加了新的cell
    UITextView *_currentTextView; //当前正在编辑的textView
    UIView *_blackView; //新建cell时遮挡背景的半透明黑色view
}

- (void)viewDidLoad {
    self.rippleImageName = @"backgroundImage.jpeg";
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initData];
    [self initUI];
}

- (void)initData
{
    _arrayData = [LPCInfoManager sharedLPCInfoManager].arrayLoveTexts;
}

- (void)initUI
{
//    [self initButton];
    [self initBlackView];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}

- (void)initButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(SCREEN_WIDTH/2 - 150/2, 15, 150, 30);
    [button setTitle:@"回家吧" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setTitleColor:RGBCOLOR(26, 213, 255) forState:UIControlStateNormal];
    [button setImage:ImageNamed(@"arrow_down") forState:UIControlStateNormal];
    button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -30, 0.0, 0.0);
    button.imageEdgeInsets = UIEdgeInsetsMake(0.0, 100, 0.0, 0.0);
    [button addTarget:self action:@selector(backHome) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)initBlackView
{
    _blackView = [[UIView alloc] initWithFrame:CGRectMake(0, self.tableView.frame.origin.y + 44, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _blackView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    _blackView.hidden = YES;
    [self.view addSubview:_blackView];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didEndAddText)];
    [_blackView addGestureRecognizer:tapGR];
}


#pragma mark - Action
//添加一个自带textfield的cell
- (void)addTFRow
{
    [_arrayData insertObject:@"" atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    stopUdpate = YES;
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    stopUdpate = NO;
    
    _isAddRow = YES;
}

-(void)cellLongPress:(UILongPressGestureRecognizer *)longRecognizer
{
    if (longRecognizer.state==UIGestureRecognizerStateBegan) {
        //成为第一响应者，需重写该方法
        [self becomeFirstResponder];
        
        //可以得到此时你点击的哪一行
        CGPoint location = [longRecognizer locationInView:self.tableView];
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];

        //复制到剪贴板
        [UIPasteboard generalPasteboard].string = _arrayData[indexPath.row];
        
        [MBProgressHUD showTipMessageInWindow:@"复制成功"];
    }
}

//点击遮挡背景
- (void)didEndAddText
{
    _blackView.hidden = YES;
    [_currentTextView resignFirstResponder];
}

- (void)backHome
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView.contentOffset.y < -44) {
        [self addTFRow];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (_isAddRow) {
        [_currentTextView becomeFirstResponder];
        _isAddRow = NO;
    }
}


#pragma mark - UITableViewDataSource、UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arrayData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    //清空复用元素
    cell.textLabel.text = @"";
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    if (((NSString *)_arrayData[indexPath.row]).length == 0) {
        UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH - 30, 44)];
        textView.delegate = self;
        textView.returnKeyType = UIReturnKeyDone;
        textView.font = [UIFont systemFontOfSize:13];
        textView.backgroundColor = [UIColor clearColor];
        textView.textContainerInset = UIEdgeInsetsMake(14, 0, 0, 0);
        textView.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        [cell.contentView addSubview:textView];
        _currentTextView = textView;
    }else {
        cell.textLabel.numberOfLines = 0;
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.text = _arrayData[indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:13];
        cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        
        //添加长按手势
        UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(cellLongPress:)];
        longPressGesture.minimumPressDuration = 1.0f;//设置长按 时间
        [cell addGestureRecognizer:longPressGesture];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [MBProgressHUD showTipMessageInWindow:@"长按复制"];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[LPCSettingManager sharedLPCSettingManager].userId isEqualToString:@"Godlike"]) { //试用版本不可执行删除操作
        [MBProgressHUD showTipMessageInWindow:@"试用版本不可执行删除操作"];
    }else {
        // 删除模型
        [_arrayData removeObjectAtIndex:indexPath.row];
        // 刷新
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [_arrayData writeToFile:PATH_LoveTexts atomically:YES];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"忘却";
}


#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    _blackView.hidden = NO;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        _blackView.hidden = YES;
        [textView resignFirstResponder];
        return FALSE;
    }
    return TRUE;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length == 0) {
        [_arrayData removeObjectAtIndex:0];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
    }else {
        [_arrayData replaceObjectAtIndex:0 withObject:textView.text];
        [_arrayData writeToFile:PATH_LoveTexts atomically:YES];
    }
    
    [self.tableView reloadData];
}




@end
